package cn.baiweigang.uu.api.swap;

import cn.baiweigang.uu.api.BaseApi;
import cn.baiweigang.uu.enums.TransferTypeEnum;
import cn.baiweigang.uu.model.AccountInfo;
import cn.baiweigang.uu.utils.LogUtil;
import com.huobi.swap.api.request.transfer.UsdtSwapTransferRequest;
import com.huobi.swap.api.response.transfer.UsdtSwapTransferResponse;
import com.huobi.swap.api.service.transfer.TransferApiServiceImpl;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class TransferSwapApi extends BaseApi {
    private TransferApiServiceImpl transferApiService;

    public boolean transfer(AccountInfo accountInfo, BigDecimal amount, TransferTypeEnum transferType) {
        try {
            init(accountInfo.getAccountName());
            String from = "swap";
            String to = "spot";
            if (transferType == TransferTypeEnum.spot_to_swap) {
                from = "spot";
                to = "swap";
            }
            UsdtSwapTransferRequest request = UsdtSwapTransferRequest.builder()
                    .from(from)
                    .to(to)
                    .currency(accountInfo.getSymbol().getCode())
                    .amount(amount.setScale(8, BigDecimal.ROUND_DOWN))
                    .build();
            UsdtSwapTransferResponse response = transferApiService.transfer(request);
            LogUtil.logInfo(response);
            if (response != null && response.getSuccess() && response.getCode() == 200 &&
                    response.getData() > 0) {
                LogUtil.logInfo(transferType.getCode() + " 划转成功");
                return true;
            }
        } catch (Throwable e) {
            LogUtil.logError("币本位永续合约和币币账户间划转异常 " + e.getMessage());
        }
        return false;
    }

    private void init(String accountName) {
        if (transferApiService == null) {
            loadByAccountName(accountName);
            transferApiService = new TransferApiServiceImpl(apiKeyInfo.getApiKey(), apiKeyInfo.getSecretKey());
        }
    }
}
